package com.king.base.service.upload.impl;

import com.king.base.config.cloud.CloudConfig;
import com.king.base.service.upload.CloudAbstractService;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import java.io.File;
import java.io.InputStream;

/**
 * @author ππ
 * @date 2020-4-23 15:43
 * 七牛云存储
 */

public class QiNiuCloudService extends CloudAbstractService {
    private UploadManager uploadManager;
    private BucketManager bucketManager;
    private String token;
    public QiNiuCloudService(CloudConfig config) {
        super(config);
    }

    private void init(){
        Configuration configuration = new Configuration(Region.autoRegion());
        uploadManager = new UploadManager(configuration);
        Auth auth = Auth.create(config.getAccessKey(),config.getSecretKey());
        token = auth.uploadToken(config.getBucket());
        bucketManager = new BucketManager(auth,configuration);
    }
    @Override
    public String upload(byte[] data, String path) {
        try {
             uploadManager.put(data, path, token);
            //解析上传成功的结果
            return config.getDomain()+"/"+path;
        }catch (Exception e){
            logger.error(e.getMessage());

        }
        return null;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        String path = getPath(suffix);
        try {
            uploadManager.put(data, path, token);
            //解析上传成功的结果
            return config.getDomain()+"/"+path;
        }catch (Exception e){
            logger.error(e.getMessage());

        }
        return null;
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            uploadManager.put(inputStream,path,token,null, null);
            return config.getDomain()+"/"+path;
        }catch (Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        String path = getPath(suffix);
        try {
            uploadManager.put(inputStream,path,token,null, null);
            return config.getDomain()+"/"+path;
        }catch (Exception e){
            logger.error(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String upload(File file) {
        return null;
    }

    @Override
    public boolean delete(String url) {
        try {
            bucketManager.delete(config.getBucket(),url);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return false;
    }

    @Override
    public void queryAll(String folder) {

    }
}
